import Request from './request'
import type { AxiosResponse } from 'axios'
import { useUserStore } from '@/stores/user'
import { HttpStatus } from '@/api/types'

const request = new Request({
  baseURL: import.meta.env.VITE_API_BASE_URL,

  interceptors: {
    requestInterceptor: (config) => {
      // 请求头添加Bearer Token
      if (config.url !== '/login') {
        const userStore = useUserStore()
        config.headers.Authorization = `Bearer ${userStore.token || localStorage.getItem('token') || sessionStorage.getItem('token')}`
      }
      return config
    },
    responseInterceptor: (response: AxiosResponse) => {
      if ((response.config as any)?.isRetry) {
        return response
      } else if (response.status && response.status >= 200 && response.status < 300) {
        return response.data !== undefined ? response.data : response
      } else {
        const msg = response?.statusText || '请求失败'
        throw new Error(msg)
      }
    },
    responseInterceptorCatch: (error) => {
      if (error.response && error.response.status === HttpStatus.UNAUTHORIZED) {
        // 检查是否是刷新令牌的请求
        const userStore = useUserStore()
        const isRefreshingToken = error.config?.url === '/auth/refresh'
        if (isRefreshingToken) {
          userStore.logout()
          return Promise.reject(new Error('刷新令牌无效，请重新登录'))
        }

        // 使用refreshtoken刷新token
        return new Promise(async (resolve, reject) => {
          try {
            await userStore.refreshToken()
            const isRetryConfig = {
              isRetry: true,
              ...error.config,
              interceptors: {},
            }
            try {
              const res = await request.request(isRetryConfig)
              resolve((res as AxiosResponse).data)
            } catch (error) {
              reject(error)
            }
          } catch (error) {
            userStore.logout()
            reject(new Error('刷新令牌失败，请重新登录'))
          }
        })
      }
      // 统一处理网络或服务端错误
      let message = '网络异常或服务器错误'
      if (error.response && error.response.data && error.response.data.message) {
        message = error.response.data.message
      } else if (error.message) {
        message = error.message
      }
      const errorRes = {
        statusCode: error.response?.status,
        message,
      }
      return Promise.reject(errorRes)
    },
  },
})

export default request
